<template>
	<view class="content">
		<view class="status_bar">
			<!-- 这里是状态栏 -->
		</view>
		
		<!-- 顶部导航 -->
		<view class="header-nav">
			<view class="back-button" @click="handleGoBack">
				<view class="back-icon-wrapper">
					<image class="back-icon" src="/static/images/icon/left-icon.png"></image>
				</view>
			</view>
			<view class="page-title">
				{{isEdit ? '編輯' + typeTitle.replace('發佈', '') : typeTitle}}
			</view>
			<view class="publish-button" @click="handleSubmit">
				{{isEdit ? '保存' : '發佈'}}
			</view>
		</view>
		
		<!-- 内容区域 -->
		<view class="content-section">
			<view class="content-card">
				<!-- 图片上传区域 -->
				<view class="image-upload-section">
					<view 
						v-for="(item, index) in images" 
						:key="index" 
						class="image-item"
					>
						<view 
							class="image-wrapper" 
							@click="handleShowImage(index)"
						>
							<u-image
								:src="item.url"
								width="180rpx"
								height="210rpx"
								radius="20rpx"
							></u-image>
							<view 
								v-if="index == 0" 
								class="cover-label"
							>
								封面
							</view>
						</view>
					</view>
					<view 
						class="add-image-button" 
						@click="handleChooseImage" 
						v-if="images.length < 6"
					>
						<view class="add-icon-wrapper">
							<u-image
								src="/static/images/icon/plus-grey.png"
								width="36rpx"
								height="36rpx"
							></u-image>
						</view>
					</view>
				</view>
				
				<!-- 标题输入 -->
				<view class="title-input-section">
					<u-input 
						name="title" 
						placeholder="請輸入標題,獲得更多瀏覽量" 
						v-model="form.title" 
						border="none" 
						maxlength="20" 
						@change="handleTitleInput"
					></u-input>
					<view class="character-count">
						{{input_count}} / 20
					</view>
				</view>
				
				<!-- 内容编辑器 -->
				<view class="editor-section">
					<editor 
						id="editor" 
						placeholder="請輸入介紹文字，有趣的詳細內容可加分！"
						@input="handleEditorInput"
						@ready="handleEditorReady" 
					>
					</editor>
				</view>
				
				<!-- 编辑器工具栏 -->
				<view class="editor-toolbar">
					<view class="toolbar-left">
						<view @click="handleOpenUserSearch">
							<u-image
								src="/static/images/icon/at.png"
								width="40rpx"
								height="40rpx"
							></u-image>
						</view>
						<view 
							class="topic-button" 
							@click="handleOpenTopicSearch"
						>
							<u-image
								src="/static/images/icon/well-no.png"
								width="40rpx"
								height="40rpx"
							></u-image>
						</view>
					</view>
					<view class="character-count">
						{{textarea_count}} / 500
					</view>
				</view>
			</view>
		</view>
		
		<!-- 分类选择 -->
		<view class="content-section">
			<view class="list-item" @click="handleOpenClassify">
				<view class="list-item-title">
					<view class="item-title">
						<view class="title">分類</view>
						<view class="required-mark">*</view>
					</view>
					<view :class="{'item-subtitle':!classifyCheck,'item-subtitle-active':classifyCheck}" >
						{{form.classify}}
					</view>
				</view>
				<view>
					<u-image
						src="/static/images/icon/right-icon.png"
						width="40rpx"
						height="40rpx"
					></u-image>
				</view>
			</view>
		</view>
		
		<!-- 预约信息 -->
		<view class="content-section">
			<view v-if="typeItem != 3" class="list-item" @click="handleOpenType">
				<view class="list-item-title">
					<view class="item-title">
						<view class="title">預約類型</view>
						<view class="required-mark">*</view>
					</view>
					<view :class="{'item-subtitle':!typeNameCheck,'item-subtitle-active':typeNameCheck}" >
						{{typeName}}
					</view>
				</view>
				<view>
					<u-image
						src="/static/images/icon/right-icon.png"
						width="40rpx"
						height="40rpx"
					></u-image>
				</view>
			</view>
			
			<view 
				v-if="form.type == 1" 
				@click="handleOpenArea" 
				class="list-item" 
			>
				<view class="list-item-title">
					<view class="item-title">
						<view class="title">服務地址</view>
						<view class="required-mark">*</view>
					</view>
					<view class="item-subtitle" >
						{{areaName}}
					</view>
				</view>
				<view>
					<u-image
						src="/static/images/icon/right-icon.png"
						width="40rpx"
						height="40rpx"
					></u-image>
				</view>
			</view>
			
			<view 
				v-if="form.type == 2 || typeItem == 3" 
				@click="handleOpenAddress" 
				class="list-item"
			>
				<view class="list-item-title">
					<view class="item-title">
						<view class="title">{{ typeItem == 3?'地點':'服務地址' }} </view>
						<view class="required-mark">*</view>
					</view>
					<view class="item-subtitle" >
						{{ city_address }}
					</view>
				</view>
				<view>
					<u-image
						src="/static/images/icon/right-icon.png"
						width="40rpx"
						height="40rpx"
					></u-image>
				</view>
			</view>
			
			<view 
				v-if="typeItem != 3" 
				class="list-item" 
				@click="handleOpenMeter"
			>
				<view class="list-item-title">
					<view class="item-title">
						<view class="title">收費計價</view>
						<view class="required-mark">*</view>
					</view>
					<view class="item-subtitle">
						{{priceName}}
					</view>
				</view>
				<view>
					<u-image
						src="/static/images/icon/right-icon.png"
						width="40rpx"
						height="40rpx"
					></u-image>
				</view>
			</view>
			
			<view 
				v-if="typeItem != 3" 
				class="list-item" 
				@click="handleOpenAppointment"
			>
				<view class="list-item-title">
					<view class="item-title">
						<view class="title">預約時間</view>
						<view class="required-mark">*</view>
					</view>
					<view class="item-subtitle" >
						{{appointmentStr}}
					</view>
				</view>
				<view>
					<u-image
						src="/static/images/icon/right-icon.png"
						width="40rpx"
						height="40rpx"
					></u-image>
				</view>
			</view>
		</view>
		
		<!-- 图片查看弹窗 -->
		<u-overlay :show="showImg" opacity="1" :duration="400">
			<view class="image-preview-container">
				<view class="image-preview">
					<image
						:src="picUrl"
						mode="widthFix"
						class="preview-image"
					></image>
				</view>
				<view class="preview-actions">
					<view class="action-button" @click="handleDeleteImage">刪除</view>
					<view class="action-button" @click="handleCloseImagePreview">完成</view>
				</view>
			</view>
		</u-overlay>
		
		<!-- 用户搜索弹窗 -->
		<u-popup :show="showUserPopup" @close="showUserPopup = false" :round="60">
			<view class="search-popup">
				<view>
					<u-search 
						placeholder="搜尋"
						:focus="searchUserFocus"
						v-model="keyword" 
						@change="handleUserSearch"
					></u-search>
				</view>
				<view>
					<view 
						v-for="(item, index) in userList" 
						:key="index" 
						class="search-result-item" 
						@click="handleSelectUser(index)"
					>
						<view>
							<u--image
								:src="item.url"
								shape="circle"
								width="56rpx"
								height="56rpx"
							></u--image>
						</view>
						<view class="result-title">
							<text 
								v-for="(segment, index_) in item.highlightTitle" 
								:key="index_" 
								:class="{ 'highlight-text': segment.highlight }"
							>
								{{segment.text}}
							</text>
						</view>
					</view>
					<view 
						v-if="userList.length == 0" 
						class="empty-result"
					>
						没有找到符合条件的用户
					</view>
				</view>
			</view>
		</u-popup>
		
		<!-- 话题搜索弹窗 -->
		<u-popup :show="showTopicPopup" @close="showTopicPopup = false" :round="60">
			<view class="search-popup">
				<view>
					<u-search
						placeholder="搜尋"
						:focus="searchTopicFocus"
						v-model="keyword" 
						@change="handleTopicSearch"
					></u-search>
				</view>
				<view>
					<view 
						v-for="(item, index) in topicList" 
						:key="index" 
						class="search-result-item" 
						@click="handleSelectTopic(index)"
					>
						<view>
							<u--image
								src="/static/images/icon/topic.png"
								shape="circle"
								width="56rpx"
								height="56rpx"
							></u--image>
						</view>
						<view class="result-title">
							<text 
								v-for="(segment, index_) in item.highlightTitle" 
								:key="index_" 
								:class="{ 'highlight-text': segment.highlight }"
							>
								{{segment.text}}
							</text>
						</view>
					</view>
					<view 
						v-if="topicList.length == 0" 
						class="empty-result"
					>
						<view class="empty-text">没有找到符合条件的结果</view>
						<view 
							v-if="keyword.length > 0" 
							class="create-topic-section"
						>
							<view 
								class="create-topic-button" 
								@click="handleCreateTopic"
							>
								創建成新話題
							</view>
						</view>
					</view>
				</view>
			</view>
		</u-popup>
		
		<!-- 预约类型弹窗 -->
		<u-popup :show="showType" mode="bottom" round="48rpx" @close="showType=false">
			<view class="type-popup">
				<view class="popup-header">
					<view class="header-action" @click="handleCloseType">取消</view>
					<view class="header-title">預約類型</view>
					<view class="header-action confirm-button" @click="handleSetType">選擇</view>
				</view>
				<view class="popup-body">
					<view class="type-list">
						<view 
							class="type-item" 
							v-for="(item,index) in typeList" 
							:key="index" 
							@click="handleSelectType(item.type)"
						>
							<view class="type-icon">
								<u-image
									v-if="item.type == typeId"
									src="/static/images/icon/success-solid.png"
									width="48rpx"
									height="48rpx"
								></u-image>
								<view v-else class="type-radio"></view>
							</view>
							<view class="type-text">
								<view class="type-title">{{item.title}}</view>
								<view class="type-description">{{item.describe}}</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import { archivesPost, archivesEdit, archivesDetail, tagsSearch, userSearch, tagsAdd } from '@/config/api.js';
	
	export default {
		data() {
			return {
				isEdit: false, // 是否为编辑模式
				editId: null, // 编辑的文章ID
				typeItem: 1,
				typeTitle: '發佈任務需求',
				form: {
					type: 3,
					title: '',
					introduce: '',
					classify: '選擇分類',
					channel_address: '',
					channel_map: ''
				},
				classifyId:0,
				classifyCheck: false,
				images: [],
				input_count: 0,
				textarea_count: 0,
				showImg: false,
				picUrl: '',
				current: -1,
				keyword: '',
				tagsWord: '',
				showUserPopup: false,
				userList: [], // 查询结果
				userIds: [], // 存放用户@结果
				isFocus: false,
				showTopicPopup: false,
				topicList: [],
				topicIds: [],
				isTopicFocus: false,
				sign: '',
				showType: false,
				typeId: 0,
				typeNameCheck: false,
				typeName: '選擇類型',
				typeList: [],
				typeList_expert: [{
					type: 1,
					title: '到府',
					describe: '可至指定地點提供服務'
				}, {
					type: 2,
					title: '到店',
					describe: '您有店面，可讓顧客預約並前往體驗'
				}, {
					type: 3,
					title: '線上',
					describe: '無距離限制，彈性提供專業服務'
				}],
				typeList_task: [{
					type: 2,
					title: '指定地點',
					describe: '需讓達人至指定地點提供服務，您需提供地址'
				}, {
					type: 3,
					title: '線上',
					describe: '無距離限制，彈性提供專業服務'
				}],
				areaIds: '', // 选择的城市id集合
				areaName: '選擇區域',
				priceName: '選擇價錢',
				price: 0,
				unitValue: 1,
				editorCtx: null,
				searchUserTimeout: null,
				searchTopicTimeout: null,
				searchUserFocus: false,
				searchTopicFocus: false,
				appointmentList: [[], [], [], [], [], [], []],
				appointmentStr: "選擇時間",
				nums: 1,
				city_address: '服務地址',
				startDate:'',
				endDate:''
			}
		},
		onLoad(option) {
			this.initializePage(option);
		},
		mounted() {
			this.$nextTick(() => {
				this.searchUserFocus = true
			})
		},
		methods: {
			// ========== 页面初始化 ==========
			initializePage(option) {
				if (option.type == 'expert') {
					this.typeTitle = '發佈達人技能';
					this.typeList = this.typeList_expert;
					this.typeItem = 1;
				} else if (option.type == 'task') {
					this.typeTitle = '發佈任務需求';
					this.typeList = this.typeList_task;
					this.typeItem = 2;
				} else if (option.type == 'colony') {
					this.typeTitle = '發佈貼文';
					this.typeItem = 3;
					this.city_address = '選擇你要分享的地點';
				}
				
				// 检查是否为编辑模式
				if (option.id) {
					this.isEdit = true;
					this.editId = option.id;
					this.loadEditData(option.id);
				}
			},
			
			// ========== 加载编辑数据 ==========
			async loadEditData(id) {
				try {
					uni.showLoading({ title: '加载中...' });
					const res = await archivesDetail({ id });
					this.fillFormData(res);
					uni.hideLoading();
				} catch (error) {
					console.error('加载编辑数据失败:', error);
					uni.hideLoading();
					uni.showToast({
						icon: 'none',
						title: '加载失败'
					});
				}
			},
			
			// ========== 填充表单数据 ==========
			fillFormData(data) {
				// 基础信息
				this.form.title = data.title;
				this.form.introduce = data.description;
				this.classifyId = data.category;
				this.form.classify = '已選擇分類'; // 这里需要根据category id获取分类名称
				this.classifyCheck = true;
				
				// 图片处理
				this.images = [];
				if (data.cover) {
					this.images.push({ url: data.cover });
				}
				if (data.images && data.images.length > 0) {
					data.images.forEach(img => {
						if (img !== data.cover) {
							this.images.push({ url: img });
						}
					});
				}
				
				// 价格信息
				this.price = parseFloat(data.price);
				this.unitValue = data.unit;
				this.nums = data.num;
				this.priceName = `NT $${data.price}/${this.getUnitName(data.unit)}`;
				
				// 服务类型
				this.form.type = data.service_type;
				this.typeId = data.service_type;
				this.typeName = this.getServiceTypeName(data.service_type);
				this.typeNameCheck = true;
				
				// 地址信息
				if (data.address) {
					this.form.channel_address = data.address;
					this.city_address = data.address;
				}
				if (data.latitude_longitude) {
					this.form.channel_map = data.latitude_longitude;
				}
				
				// 标签和用户
				if (data.tags) {
					this.topicIds = data.tags.split(',').filter(id => id);
				}
				if (data.users) {
					this.userIds = data.users.split(',').filter(id => id);
				}
				
				// 时间信息
				if (data.start) this.startDate = data.start;
				if (data.end) this.endDate = data.end;
				
				// 处理预约时间
				if (data.times) {
					this.processTimesData(data.times);
				}
				
				// 更新字符计数
				this.handleTitleInput();
				
				// 延迟更新编辑器内容，确保编辑器已准备好
				setTimeout(() => {
					this.updateEditorContent(this.form.introduce);
				}, 500);
			},
			
			// ========== 处理时间数据 ==========
			processTimesData(times) {
				const days = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'];
				this.appointmentList = [[], [], [], [], [], [], []];
				
				days.forEach((day, index) => {
					if (times[day]) {
						const timeSlots = times[day].split(',');
						timeSlots.forEach(slot => {
							if (slot.includes('-')) {
								// 时间段处理
								const [start, end] = slot.split('-').map(t => parseInt(t.split(':')[0]));
								for (let hour = start; hour <= end; hour++) {
									this.appointmentList[index].push(hour);
								}
							} else {
								// 单个时间点
								const hour = parseInt(slot.split(':')[0]);
								this.appointmentList[index].push(hour);
							}
						});
					}
				});
				
				this.appointmentStr = '已選擇';
			},
			
			// ========== 获取单位名称 ==========
			getUnitName(unit) {
				const units = {
					1: '小時',
					2: '天',
					3: '筆'
				};
				return units[unit] || '';
			},
			
			// ========== 获取服务类型名称 ==========
			getServiceTypeName(type) {
				const allTypes = [...this.typeList_expert, ...this.typeList_task];
				const found = allTypes.find(item => item.type === type);
				return found ? found.title : '選擇類型';
			},
			
			// ========== 导航相关 ==========
			handleGoBack() {
				uni.navigateBack();
			},
			
			// ========== 输入处理 ==========
			handleTitleInput() {
				this.input_count = this.form.title.replace(/[\s\n]/g, '').length;
			},
			
			// ========== 富文本编辑器相关 ==========
			handleEditorReady() {
				uni.createSelectorQuery()
					.select('#editor')
					.context(res => {
						this.editorCtx = res.context
					}).exec()
			},
			
			handleEditorInput(e) {
				this.form.introduce = e.detail.html
				// 统计字数
				this.textarea_count = e.detail.text.length;
				
				// 监听@或者#输入
				this.handleSymbolDetection(e.detail.html);
			},
			
			handleSymbolDetection(content) {
				let cleanString = content
					.replace(/<[^>]+>/g, '')
					.replace(/[\s\n]/g, '');
				const lastChar = cleanString.slice(-1);
				
				// 判断是否为@或#
				if (lastChar === '@') {
					this.sign = '@';
					this.showUserPopup = true;
				} else if (lastChar === '#') {
					this.sign = '#';
					this.showTopicPopup = true;
				} else {
					this.showUserPopup = false;
					this.showTopicPopup = false;
				}
			},
			
			// ========== 图片处理相关 ==========
			handleChooseImage() {
				let that = this;
				let uploadUrl = uni.$u.http.config.baseURL + '/api/home/upload'
				uni.chooseImage({
					count: 6 - this.images.length,
					success: (chooseImageRes) => {
						const tempFilePaths = chooseImageRes.tempFilePaths;
						console.log(tempFilePaths)
						for (let i = 0; i < tempFilePaths.length; i++) {
							uni.uploadFile({
								url: uploadUrl,
								header: {
									'Authorization': 'Bearer ' + uni.getStorageSync('token') // 从全局获取token
								},
								filePath: tempFilePaths[i],
								name: 'file',
								formData: {
									'type': 'cms',
									'timestamp': Date.now()
								},
								success: (uploadFileRes) => {
									let res = JSON.parse(uploadFileRes.data)
									that.images.push({
										url: res.fullurl
									});
									console.log(that.images)
								}
							});
						}
					},
					fail: (e) => {
						console.log('error', e)
					},
					complete: (res) => {
						console.log('complete', res)
					}
				});
			},
			
			handleShowImage(index) {
				console.log(this.images[index].url)
				this.picUrl = this.images[index].url;
				this.current = index;
				this.showImg = true;
			},
			
			handleCloseImagePreview() {
				this.picUrl = '';
				this.current = -1;
				this.showImg = false;
			},
			
			handleDeleteImage() {
				this.images.splice(this.current, 1);
				this.handleCloseImagePreview();
			},
			
			// ========== 用户搜索相关 ==========
			handleOpenUserSearch() {
				this.userList = [];
				this.showUserPopup = true;
			},
			
			handleUserSearch() {
				let that = this;
				that.userList = [];
				if (that.keyword.length == 0) return;
				uni.showLoading();
				clearTimeout(this.searchUserTimeout);
				this.searchUserTimeout = setTimeout(() => {
					let data = {
						keyword: that.keyword
					}
					userSearch(data).then((res) => {
						for (let o in res) {
							that.userList.push({
								id: res[o].id,
								url: res[o].avatar,
								title: res[o].nickname,
								highlightTitle: []
							})
						}
						that.setHighlightTitle(that.userList)
						uni.hideLoading()
					}).catch((e) => {
						console.log('error', e)
					})
				}, 500);
			},
			
			handleSelectUser(index) {
				let that = this;
				let str = '';
				if (this.sign == '') {
					str = that.form.introduce + `<a href="/pages/home/user?id=${that.userList[index].id}" style="color:#337F89;text-decoration: none;">${that.userList[index].title}&nbsp;</a>`
				} else {
					// 在符号处
					str = that.processRichText(that.form.introduce, '@', that.userList[index].id, that.userList[index].title)
				}
				that.userIds.push(that.userList[index].id);
				that.sign = '';
				that.keyword = '';
				that.form.introduce = str;
				that.showUserPopup = false;
				this.updateEditorContent(str);
			},
			
			// ========== 话题搜索相关 ==========
			handleOpenTopicSearch() {
				this.topicList = [];
				this.showTopicPopup = true;
			},
			
			handleTopicSearch() {
				let that = this;
				that.topicList = [];
				if (that.keyword.length == 0) return;
				uni.showLoading();
				clearTimeout(this.searchTopicTimeout);
				this.searchTopicTimeout = setTimeout(() => {
					let data = {
						keyword: that.keyword
					}
					tagsSearch(data).then((res) => {
						console.log('sucess', res)
						for (let o in res) {
							that.topicList.push({
								id: res[o].id,
								title: res[o].title,
								highlightTitle: []
							})
						}
						that.setHighlightTitle(that.topicList)
						uni.hideLoading()
					}).catch((e) => {
						console.log('error', e)
					})
				}, 500);
			},
			
			handleSelectTopic(index) {
				let id = this.topicList[index].id;
				let title = this.topicList[index].title;
				this.insertTags(id, title);
			},
			
			handleCreateTopic() {
				let that = this;
				let parames = {
					title: this.keyword
				}
				tagsAdd(parames).then((res) => {
					console.log('sucess', res)
					// 添加到对话框
					that.insertTags(res, that.keyword);
				}).catch((e) => {
					console.log('error', e)
				})
			},
			
			// ========== 标签处理 ==========
			insertTags(id, title) {
				let that = this;
				let str = '';
				if (this.sign == '') {
					str = that.form.introduce + `<a href="/pages/home/topic?id=${id}" style="color:#337F89;text-decoration: none;">#${title}&nbsp;</a>`
				} else {
					// 在符号处
					str = that.processRichText(that.form.introduce, '#', id, title)
				}
				console.log(str)
				that.sign = '';
				that.keyword = '';
				that.form.introduce = str;
				that.showTopicPopup = false;
				that.updateEditorContent(str);
				that.topicIds.push(id);
			},
			
			// ========== 编辑器内容更新 ==========
			updateEditorContent(content) {
				uni.createSelectorQuery()
					.in(this)
					.select('#editor')
					.context(res => {
						this.editorCtx = res.context
						// 初始化赋值
						this.editorCtx.setContents({
							html: content,
							success: () => {}
						})
					}).exec()
			},
			
			// ========== 文本处理工具方法 ==========
			setHighlightTitle(data) {
				for (let i in data) {
					console.log(data[i].title)
					data[i].highlightTitle = this.highlightTitle(data[i].title);
				}
			},
			
			highlightTitle(title) {
				if (!this.keyword) {
					// 无关键词时显示完整标题
					return [{
						text: title,
						highlight: false
					}];
				}
				
				const segments = [];
				let remainingText = title;
				const lowerKeyword = this.keyword; // 不区分大小写
				
				// 循环切割匹配部分
				while (remainingText) {
					const lowerText = remainingText;
					const index = lowerText.indexOf(lowerKeyword);
			
					if (index === -1) {
						segments.push({
							text: remainingText,
							highlight: false
						});
						break;
					}
			
					// 切割非匹配部分
					if (index > 0) {
						segments.push({
							text: remainingText.slice(0, index),
							highlight: false
						});
					}
			
					// 切割匹配部分
					segments.push({
						text: remainingText.slice(index, index + this.keyword.length),
						highlight: true
					});
			
					// 剩余文本继续处理
					remainingText = remainingText.slice(index + this.keyword.length);
				}
				return segments;
			},
			
			processRichText(content, symbol, id, title) {
				const pattern = new RegExp(`(${symbol})`);
				if (symbol == '@') {
					return content.replace(pattern, `<a href="/pages/home/user?id=${id}" style="color:#337F89;text-decoration: none;">@${title}&nbsp;</a>`);
				} else {
					return content.replace(pattern, `<a href="/pages/home/topic?id=${id}" style="color:#337F89;text-decoration: none;">${title}&nbsp;</a>`);
				}
			},
			
			// ========== 分类选择 ==========
			handleOpenClassify() {
				let that = this;
				uni.navigateTo({
					url: '/pages/demand/filter',
					events: {
						// 定义接收事件
						acceptData: (data) => {
							console.log('接收数据:', data);
							that.classifyId = data.data[0].id;
							that.form.classify = data.data[0].title;
							that.classifyCheck = true;
						}
					},
					success: (res) => {
						// 向B页面传递初始数据（可选）
						res.eventChannel.emit('initData', {
							maxCount: 1,
							selectedIds: that.classifyId ? [that.classifyId] : []
						});
					}
				});
			},
			
			// ========== 类型选择相关 ==========
			handleOpenType() {
				this.typeId = this.form.type;
				this.showType = true;
			},
			
			handleCloseType() {
				this.typeId = 0;
				this.showType = false;
			},
			
			handleSelectType(type) {
				this.typeId = type;
			},
			
			handleSetType() {
				this.form.type = this.typeId;
				for (let i in this.typeList) {
					if (this.typeList[i].type == this.form.type) {
						this.typeName = this.typeList[i].title;
						this.typeNameCheck = true;
					}
				}
				if (this.typeId == 3) {
					// 线上，默认发全台北
					let citys = [];
					for (let i = 43; i <= 65; i++) {
						citys.push(i);
					}
					this.areaIds = citys.join(',');
				}
				this.handleCloseType();
			},
			
			// ========== 地址选择相关 ==========
			handleOpenArea() {
				let that = this;
				uni.navigateTo({
					url: '/pages/demand/city?type=' + this.typeItem,
					events: {
						// 定义接收事件
						acceptData: (data) => {
							console.log('接收数据:', data);
							that.areaIds = data.city.join(',');
							that.areaName = data.name.join(',');
						}
					},
					success: (res) => {
						// 向B页面传递初始数据（可选）
						// res.eventChannel.emit('initData', { type: 1 });
					}
				});
			},
			
			handleOpenAddress() {
				let that = this;
				uni.navigateTo({
					url: '/pages/demand/address',
					events: {
						// 定义接收事件
						acceptData: (data) => {
							console.log('接收数据:', data.data);
							that.city_address = data.data.cityName + data.data.street + data.data.room
							that.form.channel_address = that.city_address;
							that.form.channel_map = data.data.longitude + ',' + data.data.latitude;
							// 地址选择城市id判断
							that.handleProcessAddressCountry(data.data.countryId);
						}
					},
					success: (res) => {
						// 向B页面传递初始数据（可选）
						// res.eventChannel.emit('initData', { type: 1 });
					}
				});
			},
			
			handleProcessAddressCountry(countryId) {
				let citys = [];
				if (countryId == 1) {
					// 台湾地区
					for (let i = 43; i <= 65; i++) {
						citys.push(i);
					}
					this.areaIds = citys.join(',');
				} else if (countryId == 2) {
					for (let i = 66; i <= 78; i++) {
						citys.push(i);
					}
					this.areaIds = citys.join(',');
				} else if (countryId == 3) {
					this.areaIds = 41;
				} else if (countryId == 4) {
					this.areaIds = 42;
				} else {
					for (let i = 41; i <= 78; i++) {
						citys.push(i);
					}
					this.areaIds = citys.join(',');
				}
			},
			
			// ========== 价格设置 ==========
			handleOpenMeter() {
				let that = this;
				uni.navigateTo({
					url: '/pages/demand/meter',
					events: {
						// 定义接收事件
						acceptData: (data) => {
							console.log('接收数据:', data);
							that.priceName = 'NT $' + data.price + '/' + data.unit;
							that.price = data.price;
							that.unitValue = data.unitValue
							that.nums = data.nums
						}
					},
					success: (res) => {
						// 向B页面传递初始数据（可选）
						// res.eventChannel.emit('initData', { type: 1 });
					}
				});
			},
			
			// ========== 时间设置 ==========
			handleOpenAppointment() {
				let that = this;
				uni.navigateTo({
					url: '/pages/demand/appointment',
					events: {
						// 定义接收事件
						acceptData: (data) => {
							console.log('時間:', data);
							if (data.data.every(subArr => subArr.length === 0)) {
								that.appointmentStr = '選擇時間'
								that.appointmentList = [
									[],
									[],
									[],
									[],
									[],
									[],
									[]
								]
							} else {
								that.appointmentStr = '已選擇';
								that.appointmentList = data.data;
								that.startDate = data.start;
								that.endDate   = data.end;
							}
						}
					},
					success: (res) => {
						// 向B页面传递初始数据（可选）
						res.eventChannel.emit('initData', {
							times: that.appointmentList
						});
					}
				});
			},
			
			// ========== 提交处理 ==========
			handleSubmit() {
				let that = this;
				
				// 数据验证
				if (that.images.length == 0) {
					uni.showToast({
						icon: 'none',
						title: "封面不能為空"
					})
					return;
				}
				
				let submitData = this.prepareSubmitData();
				
				// 根据是否为编辑模式调用不同的API
				const apiCall = this.isEdit ? archivesEdit : archivesPost;
				
				apiCall(submitData).then((res) => {
					console.log('sucess', res)
					// success
					uni.showToast({
						icon: 'none',
						title: this.isEdit ? "保存成功" : "發佈成功"
					})
					setTimeout(() => {
						uni.switchTab({
							url: '/pages/home/index'
						});
					}, 1000)
				}).catch((e) => {
					console.log('error', e)
				})
			},
			
			prepareSubmitData() {
				let img = Object.values(this.images)
					.map(item => item.url)
					.join(',');
					
				let weekTimes = this.formatAppointmentTimes();
				let tags = this.topicIds.length == 0?'':this.topicIds.join(',');
				let users = this.userIds.length == 0?'':this.userIds.join(',');
					
				const baseData = {
					type: this.typeItem, //1技能，2任務，3贴文
					title: this.form.title,
					category: this.classifyId,//分類
					images:img,
					description:this.form.introduce,
					unit:this.unitValue,//單位(1小時,2天,3筆)
					num: this.nums,//幾天, 幾小時
					price:this.price,
					service_type:this.form.type,
					address:this.form.channel_address, //门店地址
					latitude_longitude:this.form.channel_map,
					tags: tags,
					users: users,
					citys: this.areaIds,
					start:this.startDate,
					end:this.endDate,
					times1: weekTimes[0],
					times2: weekTimes[1],
					times3: weekTimes[2],
					times4: weekTimes[3],
					times5: weekTimes[4],
					times6: weekTimes[5],
					times7: weekTimes[6]
				};
				
				// 如果是编辑模式，添加ID
				if (this.isEdit) {
					baseData.id = this.editId;
				}
				
				return baseData;
			},
			
			formatAppointmentTimes() {
				let weekTimes = [[], [], [], [], [], [], []];
				
				for (let day = 0; day < 7; day++) {
					for (let i in this.appointmentList[day]) {
						weekTimes[day].push(this.formatHourToTime(this.appointmentList[day][i]));
					}
				}
				
				return weekTimes;
			},
			
			formatHourToTime(num) {
				if (typeof num !== 'number' || num < 0 || num > 23) {
					console.warn('请输入0-23之间的数字');
					return '00:00';
				}
				  
				// 补零处理并拼接时间格式
				const hour = num.toString().padStart(2, '0');
				return `${hour}:00`;
			}
		}
	}
</script>

<style lang="scss" scoped>
	.content {
		width: 100%;
		background-color: #F6F8FA;
		min-height: 100vh;
		padding-bottom: 30rpx;
	}
	
	.status-bar {
		/* 状态栏样式 */
	}
	
	/* 顶部导航 */
	.header-nav {
		width: 100%;
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 0 16rpx;
		box-sizing: border-box;
	}
	
	.back-button {
		box-sizing: border-box;
	}
	
	.back-icon-wrapper {
		border: 2rpx solid #E5E6E8;
		border-radius: 24rpx;
		background-color: #FFF;
	}
	
	.back-icon {
		width: 36rpx;
		height: 36rpx;
		margin: 16rpx 16rpx 4rpx;
	}
	
	.page-title {
		color: #232426;
		font-size: 32rpx;
		font-weight: 500;
		padding-left: 80rpx;
	}
	
	.publish-button {
		color: #1AAEC0;
		font-size: 28rpx;
		font-weight: 400;
		border-radius: 200rpx;
		border: 2rpx solid #1AAEC0;
		padding: 14rpx 42rpx;
	}
	
	/* 内容区域 */
	.content-section {
		margin-top: 28rpx;
		width: 100%;
		box-sizing: border-box;
		padding: 0 30rpx;
	}
	
	.content-card {
		background-color: #FFF;
		border-radius: 40rpx;
	}
	
	/* 图片上传区域 */
	.image-upload-section {
		display: flex;
		overflow-x: auto;
		padding: 24rpx;
		gap: 12rpx;
		width: 90%;
	}
	
	.image-item {
		width: 180rpx;
		height: 210rpx;
		background-color: #F0F0F0;
		border-radius: 20rpx;
		flex-shrink: 0;
	}
	
	.image-wrapper {
		position: relative;
		display: inline-block;
	}
	
	.cover-label {
		position: absolute;
		bottom: 8rpx;
		left: 8rpx;
		color: #fff;
		font-size: 22rpx;
		border-radius: 20rpx;
		padding: 8rpx 20rpx;
		background-color: rgba(0, 0, 0, 0.4);
	}
	
	.add-image-button {
		width: 180rpx;
		height: 210rpx;
		background-color: #F0F0F0;
		border-radius: 20rpx;
		flex-shrink: 0;
	}
	
	.add-icon-wrapper {
		margin: 87rpx 0 0 72rpx;
	}
	
	/* 标题输入区域 */
	.title-input-section {
		border-top: 2rpx solid #FAFAFA;
		padding: 28rpx 24rpx 0;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}
	
	/* 编辑器区域 */
	.editor-section {
		border-top: 2rpx solid #FAFAFA;
		padding: 28rpx 24rpx 0;
	}
	
	/* 编辑器工具栏 */
	.editor-toolbar {
		border-top: 2rpx solid #FAFAFA;
		padding: 28rpx 24rpx;
		display: flex;
		justify-content: space-between;
	}
	
	.toolbar-left {
		display: flex;
		justify-content: flex-start;
	}
	
	.topic-button {
		margin-left: 38rpx;
	}
	
	/* 字符计数 */
	.character-count {
		color: #BEC0C5;
		font-size: 20rpx;
	}
	
	/* 列表项 */
	.list-item {
		display: flex;
		justify-content: space-between;
		box-sizing: border-box;
		padding: 34rpx 24rpx;
		background-color: #FFF;
		margin-top: 2rpx;
		align-items: center;
	}
	
	.list-item:first-of-type {
		border-top-left-radius: 24rpx;
		border-top-right-radius: 24rpx;
	}
	
	.list-item:last-of-type {
		border-bottom-left-radius: 24rpx;
		border-bottom-right-radius: 24rpx;
	}
	
	.list-item-title {
		display: flex;
		justify-content: flex-start;
		align-items: center;
	}
	
	.item-title {
		display: flex;
		justify-content: flex-start;
		align-items: center;
		width: 144rpx;
		font-size: 28rpx;
	}
	
	.item-title .title {
		color: #232426;
		font-size: 28rpx;
		font-weight: 500;
	}
	
	.required-mark {
		color: #FF3D43;
		margin-left: 10rpx;
	}
	
	.item-subtitle {
		color: #BEC0C5;
		font-size: 28rpx;
		font-weight: 500;
		margin-left: 24rpx;
		width: 400rpx;
	}
	
	.item-subtitle-active {
		color: #232426;
		font-size: 28rpx;
		font-weight: 500;
		margin-left: 24rpx;
	}
	
	/* 图片预览 */
	.image-preview-container {
		position: relative;
		width: 100vw;
		height: 100vh;
		box-sizing: border-box;
	}
	
	.image-preview {
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		width: 100%;
		text-align: center;
	}
	
	.preview-image {
		width: 100%;
	}
	
	.preview-actions {
		width: 100%;
		position: absolute;
		display: flex;
		justify-content: space-between;
		padding: 0 50rpx;
		box-sizing: border-box;
		bottom: 50rpx;
		background-color: #232426;
		padding: 20rpx 0;
	}
	
	.action-button {
		color: #FFF;
	}
	
	/* 搜索弹窗 */
	.search-popup {
		width: 100%;
		background-color: #FAFAFA;
		padding: 24rpx 48rpx;
		box-sizing: border-box;
		min-height: 550rpx;
	}
	
	.search-result-item {
		display: flex;
		justify-content: flex-start;
		align-items: center;
		margin-top: 20rpx;
	}
	
	.result-title {
		margin-left: 20rpx;
		font-size: 24rpx;
		color: #232426;
	}
	
	.highlight-text {
		color: #27C5D6;
		font-weight: bold;
	}
	
	.empty-result {
		width: 100%;
		color: rgb(131, 133, 138);
		height: 500rpx;
		// display: flex;
		// justify-content: center;
		// align-items: center;
	}
	
	.empty-text {
		width: 100%;
		text-align: center;
		margin-top: 150rpx;
	}
	
	.create-topic-section {
		width: 100%;
		margin-top: 40rpx;
	}
	
	.create-topic-button {
		border: 2rpx solid #BEC0C5;
		width: 220rpx;
		margin: 0 auto;
		text-align: center;
		padding: 8rpx 20rpx;
		font-size: 28rpx;
		border-radius: 200rpx;
	}
	
	/* 类型选择弹窗 */
	.type-popup {
		padding: 58rpx 40rpx 28rpx;
	}
	
	.popup-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}
	
	.header-action {
		color: #808690;
		font-size: 32rpx;
	}
	
	.header-title {
		color: #232426;
		font-size: 30rpx;
		font-weight: 600;
	}
	
	.confirm-button {
		color: #27C5D6;
		font-size: 32rpx;
	}
	
	.popup-body {
		margin-top: 24rpx;
	}
	
	.type-list {
		box-sizing: border-box;
	}
	
	.type-item {
		margin-top: 32rpx;
		padding: 20rpx 48rpx;
		display: flex;
		justify-content: flex-start;
		align-items: center;
		background: #F6F8FA;
		border-radius: 120rpx;
	}
	
	.type-radio {
		border-radius: 50%;
		width: 48rpx;
		height: 48rpx;
		background-color: #E5E6E8;
	}
	
	.type-text {
		margin-left: 32rpx;
		width: 500rpx;
	}
	
	.type-title {
		font-size: 28rpx;
		font-weight: 600;
	}
	
	.type-description {
		color: #6A707C;
		font-size: 24rpx;
	}
</style>